//
//  endTheTripViewController.m
//  QXDLLOrdersModule
//
//  Created by DL on 17/1/5.
//  Copyright © 2017年 DLL. All rights reserved.
//

#import "endTheTripViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "DLLApiManager.h"
#import "paymentOrderDetailsViewController.h"
#import "NoCopyTextField.h"
#import "StringIsIntOrFloat.h"
#import "HeaderMacro.h"
#import <QXYueYueModels/QXYYOrderDetailModel.h>
#import <QXYueYueModels/QXYYUserPassengerModel.h>
#import "OrderClosingManager.h"
@interface endTheTripViewController ()<UITextFieldDelegate>
/// 头像
@property (weak, nonatomic) IBOutlet UIImageView *heardImageView;
/// 手机尾号
@property (weak, nonatomic) IBOutlet UILabel *phoneTailNumberLabel;
/// 拨打电话
@property (weak, nonatomic) IBOutlet UIButton *callPhoneButton;
/// 价格
@property (weak, nonatomic) IBOutlet NoCopyTextField *fareTextField;
/// 确定
@property (weak, nonatomic) IBOutlet UIButton *determineButton;

/**
 返回按钮
 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;


@end

@implementation endTheTripViewController

+ (instancetype)shareSelf {
    return [[UIStoryboard storyboardWithName:@"Orders" bundle:nil] instantiateViewControllerWithIdentifier:@"endTheTripViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 配置UI
    [self configureUI];
    
    [self reigsterNotification];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[OrderClosingManager shareManager] openNotificationWithOrderUuid:self.ordersDetailsModel.uuid receivedNotification:^(NSNotification *aNotification) {
        
        
    }];
}

- (void)configureUI {
    
    self.heardImageView.layer.cornerRadius = self.heardImageView.frame.size.height / 2.0;
    self.heardImageView.layer.masksToBounds = YES;
    
    if (![self.userPassengerModel.face isKindOfClass:[NSNull class]] && self.userPassengerModel.face.length > 0) { // 如果值非空,并且长度大于0
        
        NSURL *url = [NSURL URLWithString:self.userPassengerModel.face];
        [self.heardImageView sd_setImageWithURL:url placeholderImage:[QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"]];
    }else {
        
        self.heardImageView.image = [QXDriverConfiguration imageWithName:@"tongyong_chencheren_icon"];
    }
    
    self.determineButton.layer.cornerRadius = 4.0;
    self.determineButton.layer.masksToBounds = YES;
    
    [self.backItem setImage:[QXDriverConfiguration imageWithName:@"nav_icon_back_white"]];
    
    // 尾号
    NSString *phone = [self.userPassengerModel.mobile substringFromIndex:7];
    self.phoneTailNumberLabel.text = [NSString stringWithFormat:@"尾号%@",phone];
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
}




/**
 注册通知
 */
- (void)reigsterNotification {
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
    
     [self.fareTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
}


/**
 textField 改变了
 */
- (void)textHasChangeAction:(NSNotification *)aNotification {
    
//    if ([aNotification.name isEqualToString:UITextFieldTextDidChangeNotification]) {
//        
//        NSString *inputContent = self.fareTextField.text;
//        if ([StringIsIntOrFloat isPureFloat:inputContent]) { // 如果是float类型
//            
//            
//            self.fareTextField.text = [self.fareTextField.text substringToIndex:[self.fareTextField.text length] > 6 ? 6 : [self.fareTextField.text length]];
//        }else {
//            
//            self.fareTextField.text = [self.fareTextField.text substringToIndex:3];
//        }
//        
//        self.fareTextField.text = [self.fareTextField.text substringToIndex:3];
//    }
}



#pragma mark -拨打电话
- (IBAction)callPhoneAction:(id)sender {
    
    NSString *phone = self.userPassengerModel.mobile;
    if (phone != nil) {
        
        NSString *telUrl = [NSString stringWithFormat:@"telprompt:%@",phone];
        
        NSURL *url = [[NSURL alloc] initWithString:telUrl];
        
        [[UIApplication sharedApplication] openURL:url];
    }
}




#pragma mark -确定费用
- (IBAction)determineAction:(id)sender {
    
    [self confirmFare];
}


#pragma mark - 返回action
- (IBAction)backAction:(UIBarButtonItem *)sender {
    
//    [self.navigationController popViewControllerAnimated:YES];
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldDidChange:(UITextField *)textField
{
    //金额
    if([textField.text rangeOfString:@"."].location == NSNotFound){
        
        // 没有小数点只能4位
        if (textField.text.length > 4) {
            textField.text = [textField.text substringToIndex:4];
        }
    }
    else{
        
        // 小数点后1位
        if(textField.text.length > [textField.text rangeOfString:@"."].location + 1){
            textField.text = [textField.text substringToIndex:[textField.text rangeOfString:@"."].location + 2];
        }
        // 不能超过8个字符
        if(textField.text.length > 6){
            
            textField.text = [textField.text substringWithRange:NSMakeRange(textField.text.length - 6, 6)];
        }
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    //不能以.结尾
    if([textField.text hasSuffix:@"."]){
        textField.text = [textField.text substringToIndex:textField.text.length-1];
    }
    if([textField.text hasPrefix:@"."]){
        textField.text = [NSString stringWithFormat:@"0%@",textField.text];
    }
}


#pragma mark - 确认费用
/**
 确认费用
 */
- (void)confirmFare {
    
    [self.fareTextField resignFirstResponder];
    
    if (self.fareTextField.text.length == 0) {
        
        MBProgressHUD *mb = [MBProgressHUD showWithText:@"请输入应收取的总费用" onView:self.view hiddenDuration:1.5];
        mb.userInteractionEnabled = YES;
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:self.ordersDetailsModel.uuid forKey:@"orderUuid"];
    [parameters setValue:@([self.fareTextField.text doubleValue]) forKey:@"actualFare"];
    
    
    __weak typeof(self) weakSelf = self;
    
    [DLLApiManager confirmFareWithParameters:parameters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        if (NetWork_Success) {
            
            
            [[OrderClosingManager shareManager] closeNotification];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_ConfirmFare object:nil];
                
                [strongSelf pushIntopaymentOrderDetailsViewController];
                
            });
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
        
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:strongSelf.view animated:YES];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
    
}

- (void)pushIntopaymentOrderDetailsViewController {
    
    paymentOrderDetailsViewController *paymentOrderDetailVC = [paymentOrderDetailsViewController shareSelf];
    paymentOrderDetailVC.title = @"订单详情";
    paymentOrderDetailVC.userPassengerModel = self.userPassengerModel;
    paymentOrderDetailVC.ordersDetailsModel = self.ordersDetailsModel;
    paymentOrderDetailVC.isPoPToRootVC = YES;
    [self.navigationController pushViewController:paymentOrderDetailVC animated:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    
    NSLog(@"endTheTripVC 销毁了");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
